package cc.holen.htool4j.util;

import cc.holen.htool4j.util.exception.BusinessException;
import cc.holen.htool4j.util.exception.ErrorCodeEnum;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;

/**
 * @Author holen.zh
 * @Date 2022-06-27
 */
public class ValidateUtils {

    /**
     * 检测对象是否为null
     *
     * @param obj
     * @param errorMessage
     * @param params
     */
    public static void checkNotNull(Object obj, String errorMessage, Object... params) {
        if (obj == null) {
            throw new BusinessException(ErrorCodeEnum.ILLEGAL_ARGUMENT.getCode(),
                    format(errorMessage, params));
        }
    }


    /**
     * 检测集合是否为empty
     *
     * @param collection
     * @param errorMessage
     * @param params
     */
    public static void checkNotEmpty(Collection collection, String errorMessage, Object... params) {
        if (CollectionUtils.isEmpty(collection)) {
            throw new BusinessException(ErrorCodeEnum.ILLEGAL_ARGUMENT.getCode(),
                    format(errorMessage, params));
        }
    }


    /**
     * 检测字符串是否为empty
     *
     * @param string
     * @param errorMessage
     * @param params
     */
    public static void checkNotEmpty(String string, String errorMessage, Object... params) {
        if (!StringUtils.hasText(string)) {
            throw new BusinessException(ErrorCodeEnum.ILLEGAL_ARGUMENT.getCode(),
                    format(errorMessage, params));
        }
    }


    /**
     * 检测条件是否为true
     *
     * @param state
     * @param errorMessage
     * @param params
     */
    public static void checkTrue(boolean state, String errorMessage, Object... params) {
        if (!state) {
            throw new BusinessException(ErrorCodeEnum.ILLEGAL_ARGUMENT.getCode(),
                    format(errorMessage, params));
        }
    }


    /**
     * 错误信息格式化
     *
     * @param message
     * @param params
     * @return
     */
    private static String format(String message, Object... params) {
        return MessageFormatUtil.format(message, params);
    }

}
